package pzl.com.androidloader;

import android.graphics.Bitmap;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import pzl.com.androidloader.loader.ImageTaskLoader;

public class Demo3Activity extends AppCompatActivity implements ImageTaskLoader.IGetDataSource {
    private EditText etImageSourceUrl;
    private ImageView ivDisplay;

    /**
     * 被观察的图片url源
     */
    private String imageUrlSource = "http://cdn.duitang.com/uploads/item/201511/21/20151121125010_ruaV5.thumb.700_0.jpeg";
    private LoaderManager.LoaderCallbacks<Bitmap> loaderCallbacks;
    private ImageTaskLoader imageTaskLoader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo3);

        initView();
        initData();
    }

    private void initView() {
        etImageSourceUrl = (EditText) findViewById(R.id.etImageSourceUrl);
        ivDisplay = (ImageView) findViewById(R.id.ivDisplay);
    }

    private void initData() {
        loaderCallbacks = new LoaderManager.LoaderCallbacks<Bitmap>() {
            @Override
            public Loader<Bitmap> onCreateLoader(int id, Bundle args) {
                if (imageTaskLoader == null) {
                    imageTaskLoader = new ImageTaskLoader(Demo3Activity.this, Demo3Activity.this);
                }
                return imageTaskLoader;
            }

            @Override
            public void onLoadFinished(Loader<Bitmap> loader, Bitmap data) {
                ivDisplay.setImageBitmap(data);
            }

            @Override
            public void onLoaderReset(Loader<Bitmap> loader) {

            }
        };
        getSupportLoaderManager().restartLoader(1, null, loaderCallbacks);
    }

    public void click(View view) {
        switch (view.getId()) {
            case R.id.btnLoadImage:
                imageUrlSource = etImageSourceUrl.getText().toString().trim();
                Toast.makeText(this, imageUrlSource, Toast.LENGTH_SHORT).show();
                imageTaskLoader.onContentChanged();
                break;
        }
    }

    @Override
    public String getImageUrlSource() {
        return imageUrlSource;
    }
}
